import {
  AllChannelsResponse,
  ArticlesResponse,
  Channel,
  UserChannelResponse,
} from '@/types/data'
import { RootThunkAction } from '@/types/store'
import http from '@/utils/http'
import differenceBy from 'lodash/differenceBy'

const CHANNEL_KEY = 'geek_channels'
export const getHome = (): RootThunkAction => {
  return async (dispatch, getState) => {
    const {
      login: { token },
    } = getState()
    if (token) {
      //登录了
      const res = await http.get<UserChannelResponse>('/user/channels')
      const { channels } = res.data.data
      // console.log('登录了', channels)
      dispatch({ type: 'home/getChannels', payload: channels })
    } else {
      //未登录
      const localChannels = JSON.parse(
        localStorage.getItem(CHANNEL_KEY) ?? '[]'
      ) as Channel[]
      if (localChannels.length === 0) {
        //本地没数据
        const res = await http.get<UserChannelResponse>('/user/channels')
        const { channels } = res.data.data
        localStorage.setItem(CHANNEL_KEY, JSON.stringify(channels))
        dispatch({ type: 'home/getChannels', payload: channels })
      } else {
        //本地有数据
        dispatch({ type: 'home/getChannels', payload: localChannels })
      }
    }
  }
}

//获取所有频道数据
export const getAllChannels = (): RootThunkAction => {
  return async (dispatch, getState) => {
    const {
      home: { channels },
    } = getState()
    const res = await http.get<AllChannelsResponse>('channels')
    const AllChannels = res.data.data.channels
    const restChannels = differenceBy(AllChannels, channels, 'id')
    dispatch({ type: 'home/getAllChannels', payload: restChannels })
  }
}
// 切换频道高亮
export const toggleChannel = (id: number): RootThunkAction => {
  return (dispatch) => {
    dispatch({ type: 'home/changeTab', payload: id })
  }
}
//删除我的频道
export const delMyChannel = (channel: Channel): RootThunkAction => {
  return (dispatch, getState) => {
    const {
      login: { token },
    } = getState()
    if (!!token) {
      // 已登录
      http.delete(`/user/channels/${channel.id}`)
    } else {
      // 未登录
      const localChannel = JSON.parse(
        localStorage.getItem(CHANNEL_KEY) ?? '[]'
      ) as Channel[]
      const userChannel = localChannel.filter((item) => item.id !== channel.id)
      localStorage.setItem(CHANNEL_KEY, JSON.stringify(userChannel))
    }
    dispatch({ type: 'home/delChannel', payload: channel })
  }
}
//添加频道
export const addChannel = (channel: Channel): RootThunkAction => {
  return (dispatch, getState) => {
    const {
      login: { token },
    } = getState()
    if (!!token) {
      //登录
      http.patch('/user/channels', { channels: [channel] })
    } else {
      // 未登录
      //把本地的取出来，添加后再存回去
      const localChannels = JSON.parse(
        localStorage.getItem(CHANNEL_KEY) ?? '[]'
      ) as Channel[]
      const userChannels = [...localChannels, channel]
      localStorage.setItem(CHANNEL_KEY, JSON.stringify(userChannels))
    }
    dispatch({ type: 'home/addChannel', payload: channel })
  }
}
//列表数据
export const getArticleList = (
  channel_id: number,
  timestamp: string
): RootThunkAction => {
  return async (dispatch) => {
    const res = await http.get<ArticlesResponse>('/articles', {
      params: {
        channel_id,
        timestamp,
      },
    })
    // console.log(res)
    dispatch({
      type: 'home/getChannelArticle',
      payload: {
        channelId: channel_id,
        article: res.data.data,
      },
    })
  }
}
//下拉刷新最新数据
export const getNewestArticleList = (
  channelI: number,
  timestamp: string | null
): RootThunkAction => {
  return async (dispatch) => {
    const res = await http.get<ArticlesResponse>('articles', {
      params: {
        channel_id: channelI,
        timestamp,
      },
    })
    dispatch({
      type: 'home/getNewestChannelArticle',
      payload: {
        channelI,
        articl: res.data.data,
      },
    })
  }
}
